package com.lz.library.extension

import android.content.Context
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

/**
 *  author: you : 2020/05/14
 */

/**
 * 确保文件存在 要拷贝与拷贝的目录都需要存在
 * @param newFile 文件或文件夹拷贝
 * @param buffer 字节缓冲
 */
fun File.copyFiles(newFile: File, buffer: ByteArray = ByteArray(1024 * 4)) {
    val cpNewFile = File(newFile, this.name)
    if (this.isDirectory) {
        if (!cpNewFile.exists()) cpNewFile.mkdir()
        this.listFiles()?.forEach { it.copyFiles(cpNewFile, buffer) }
    } else {
        try {
            FileInputStream(this).use { fis ->
                FileOutputStream(cpNewFile).use { fos ->
                    var byteCount: Int
                    while (fis.read(buffer).let { byteCount = it; it != -1 }) {
                        fos.write(buffer, 0, byteCount)
                    }
                }
            }
        } catch (_: Exception) {
        }
    }
}

/**
 * 拷贝asset目录下的文件/文件夹, 要拷贝与拷贝的目录需要存在
 * @param assetDir assets根目录
 * @param newFile 需要拷贝到的目录
 * @param buffer 字节缓冲
 */
fun Context.copyAssetFiles(assetDir: String, newFile: File, buffer: ByteArray = ByteArray(1024 * 4)) {
    val listDir = assets.list(assetDir)
    if (listDir != null && listDir.isNotEmpty()) {
        File(newFile, assetDir).also { if (!it.exists()) it.mkdir() }
        listDir.forEach { copyAssetFiles("$assetDir/$it", newFile, buffer) }
    } else {
        try {
            assets.open(assetDir).use { ins ->
                FileOutputStream(File(newFile, assetDir)).use { fos ->
                    var byteCount: Int
                    while (ins.read(buffer).let { byteCount = it; it != -1 }) {
                        fos.write(buffer, 0, byteCount)
                    }
                }
            }
        } catch (_: Exception) {
        }
    }
}
